package com.framework.bdf4j.sysadm.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.enums.DictTypeEnum;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.sysadm.entity.SysDict;
import com.framework.bdf4j.sysadm.entity.SysDictItem;
import com.framework.bdf4j.sysadm.mapper.SysDictItemMapper;
import com.framework.bdf4j.sysadm.service.SysDictItemService;
import com.framework.bdf4j.sysadm.service.SysDictService;

import lombok.AllArgsConstructor;

/**
 * 字典项
 *
 */
@Service
@AllArgsConstructor
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {
	private final SysDictService dictService;

	/**
	 * 删除字典项
	 *
	 * @param id 字典项ID
	 * @return
	 */
	@Override
	@CacheEvict(value = Constants.DICT_DETAILS, allEntries = true)
	public R removeDictItem(Integer id) {
		//根据ID查询字典ID
		SysDictItem dictItem = this.getById(id);
		SysDict dict = dictService.getById(dictItem.getDictId());
		// 系统内置
		if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
			return R.failed("系统内置字典项目不能删除");
		}
		return R.ok(this.removeById(id));
	}

	/**
	 * 更新字典项
	 *
	 * @param item 字典项
	 * @return
	 */
	@Override
	@CacheEvict(value = Constants.DICT_DETAILS, allEntries = true)
	public R updateDictItem(SysDictItem item) {
		//查询字典
		SysDict dict = dictService.getById(item.getDictId());
		// 系统内置
		if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
			return R.failed("系统内置字典项目不能修改");
		}
		return R.ok(this.updateById(item));
	}
	
	@Override
    @Cacheable(value = Constants.DICT_DETAILS, unless = "#result == null")
    public Map<String, List<SysDictItem>> selectDictionaryInfo() {
        Map<String,List<SysDictItem>> dictMap = new HashMap<String,List<SysDictItem>>();
        List<SysDict> parentList = dictService.list(new QueryWrapper<SysDict>().eq("del_flag", "0"));
        
        for(SysDict pb : parentList)
        {            
            List<SysDictItem> dictList = this.list(new QueryWrapper<SysDictItem>().eq("dict_id", pb.getId()).orderByAsc("sort"));
            dictMap.put(pb.getType(), dictList);
        }

        return dictMap;
    }
}
